package com.weme.chat

import android.app.AlertDialog
import android.os.Bundle
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.gson.Gson
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.osom.proto.message.NetworkOuterClass.LoginRequest
import com.weme.chat.dialog.AccountDialog
import com.weme.chat.viewmode.LoginViewMode
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.manager.SocketConnectManager.errorService
import com.weme.common.network.JumpMainBean
import com.weme.common.network.LOGIN_TYPE
import com.weme.common.util.*
import com.weme.google.GoogleLoginHelper
import com.weme.login.databinding.ActivityLoginBinding
import dev.kratos.api.user_server.v1.UserLoginReply
import dev.kratos.api.user_server.v1.UserLoginRequest
import me.jessyan.autosize.AutoSize

@Route(path = ARouterPaths.LOGIN_ACTIVITY)
class LoginActivity : BaseMvvmActivity<ActivityLoginBinding, LoginViewMode>() {
    private lateinit var alertDialog: AlertDialog

    override fun initView(savedInstanceState: Bundle?) {

        Log.e("device", DeviceUtils.getFirstInstallTime(this).toString())
        alertDialog = createProgressDialog()
        initOnclick()

        mBinding.tvAppName.setGradientText(com.example.resources.R.color.startColor, com.example.resources.R.color.endColor)
        setSevicesSpan()
        val loginType = AppMkHelper.decodeString(LOGIN_TYPE)
        val parsedArray = Gson().fromJson(loginType, IntArray::class.java)

        parsedArray.forEach {
            when (it) {
                0 -> mBinding.tvFast.visible()
                1 -> mBinding.frGoogleBtn.visible()
                2 -> mBinding.frFbBtn.visible()
                3 -> mBinding.tvAccount.visible()
            }
        }



     LiveEventBus.get<Any>(LiveConfig.NET_WORK_LOGIN).observe(this) {
            if(it  is UserLoginReply){
                handleUserLogin(it)
            }else if(it is JumpMainBean){
                ARouterHelper.navigateToActivity(this@LoginActivity, ARouterPaths.MAIN_ACTIVITY)
                finish()
            }
        }

        Log.e("tag", "上次登录方式"+AppMkHelper.decodeInt(AppMkHelper.LOGIN_LAST, 0).toString())
        when (AppMkHelper.decodeInt(UserMKHelper.LOGIN_LAST, -1)) {
            0 -> {
                mBinding.frFastLast.visible()
                mBinding.tvGoogleLast.gone()
                mBinding.frGoogleLast.gone()
                mBinding.tvFbLast.gone()
                mBinding.frFbLast.gone()
            }
            1 -> {
                mBinding.tvGoogleLast.visible()
                mBinding.frGoogleLast.visible()
                mBinding.tvFbLast.gone()
                mBinding.frFbLast.gone()
            }
            2 -> {
                mBinding.tvGoogleLast.gone()
                mBinding.frGoogleLast.gone()
                mBinding.tvFbLast.visible()
                mBinding.frFbLast.visible()
            }
        }
        errorService.observe(this) {
            alertDialog.dismiss()
            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
        }


        //        SocketConnectManager.openService.observe(this){
        //            if(!TextUtils.isEmpty(UserMKHelper.decodeString(UserMKHelper.SESSION))){
        //                loginAgora(UserMKHelper.decodeLong(UserMKHelper.UID).toString(),UserMKHelper.decodeString(UserMKHelper.TOKEN))
        //            }
        //            loadingDialog?.dismiss()
        //        }

    }


    private var clickCount = 0
    private fun handleButtonClick() {
        clickCount++
        if (clickCount >= 10) { // 当点击次数达到5次时执行操作
            if (mBinding.tvFast.visibility == View.VISIBLE) {
                mBinding.tvFast.gone()
            } else {
                mBinding.tvFast.visible()
            } // 重置点击次数
            clickCount = 0
        }
    }

    private fun initOnclick() {
        mBinding.imLogo.setOnClickListener {
            handleButtonClick()
        }
        mBinding.tvAccount.setOnFastClickListener {
            val dialog = AccountDialog()
            dialog.show(supportFragmentManager, "AccountDialog")
        }
        mBinding.vBack.setOnFastClickListener {}
        mBinding.tvFast.setOnFastClickListener { //     if (isNetworkAvailable()) {
            //         showToast("开始游客登录")


            val fastLogin = UserLoginRequest.newBuilder().setPlatform("visitor").setDeviceID(DeviceId.getAndroidId().toString()).setGender(1).build()
            viewModel.fastLoginApi(fastLogin) //            } else {
            //                showToast("无法访问网络")
            //                XXPermissions.with(this).permission("android.permission.INTERNET").request { permissions, allGranted ->
            //                    val fastLogin = UserLoginRequest.newBuilder().setPlatform("visitor").setDeviceID(DeviceUtils.getDeviceId().toString()).setGender(1).build()
            //                    viewModel.fastLoginApi(fastLogin)
            //                }
            //            }

        }
        mBinding.calGoogle.setOnFastClickListener {
            setScreenWidthHeight()
            AutoSize.autoConvertDensityOfCustomAdapt(this, this)

            val isGooglePlayServicesAvailable: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)
            if (isGooglePlayServicesAvailable == ConnectionResult.SUCCESS) {
                alertDialog.show()
                resultLauncher.launch(GoogleLoginHelper.createGoogleIntent(this))
            } else {

                showToast("Google Play服务不可用，无法进行Google登录等操作")
            }
        }
        mBinding.calFb.setOnFastClickListener { //            FaceBookHelper.login(this, success = {
            //                it.accessToken.also { token -> getFbUserInfo(token) }
            //            }, logicerror = { e ->
            ////                dismissDialog()
            ////                showDialog(e.message ?: "login error")
            //
            //            }, cancel = {  })
        }
    }

    //    private fun getFbUserInfo(accessToken: AccessToken) {
    //        val graphRequest = GraphRequest.newMeRequest(accessToken) { `object`, _ ->
    //            try {
    //                if (`object` != null) {
    //                    val name = `object`.optString("name")
    //                    val gender = `object`.optString("gender")
    //                    val birthday = `object`.optString("birthday");
    //                    //这里获取的头像是50*50
    //                    val picture =
    //                        `object`.optJSONObject("picture")?.optJSONObject("data")?.optString("url")
    //                            ?: ""
    //
    //                }
    //            } catch (e: Exception) {
    //               // dismissDialog()
    //                e.printStackTrace()
    //            }
    //        }
    //        val parameters = Bundle()
    //        parameters.putString("fields", "id,name,gender,picture,birthday")
    //        graphRequest.parameters = parameters
    //        graphRequest.executeAsync()
    //    }

    private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        it.data?.run {
            setScreenWidthHeight()
            AutoSize.autoConvertDensityOfCustomAdapt(this@LoginActivity, this@LoginActivity)
            GoogleLoginHelper.handleIntent(this, result = { id, token ->
                fireBaseAuthGoogle(id, token)
            }, block = {

                showToast("google登录取消")
                alertDialog.dismiss()
                ImmersionBar.with(this@LoginActivity).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
            })
        }
    }

    private fun fireBaseAuthGoogle(id: String, idToken: String) { //        val tokenId = id + "&" + idToken
        //        val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        //        val clipData = ClipData.newPlainText("Label", tokenId)
        //        clipboardManager.setPrimaryClip(clipData)
        //        println("google-login:${idToken}")
        //   showToast("拿到googletoken  并复制到粘贴板")
        val fastLogin = UserLoginRequest.newBuilder().setPlatform("google").setGoogleOpenID(id).setGoogleToken(idToken).setDeviceID(DeviceId.getAndroidId().toString()).setGender(1).build()
        viewModel.fastGoogleLoginApi(fastLogin)
    }

    private fun setSevicesSpan() { // 创建包含所有文本的 SpannableString
        val fullText = getString(com.example.resources.R.string.login_terms_of_service) + System.lineSeparator() + getString(com.example.resources.R.string.login_terms_of_service_end) // 获取整个文本
        val termsOfServiceText = getString(com.example.resources.R.string.login_terms_of_service_link)
        val privacyPolicyText = getString(com.example.resources.R.string.login_privacy_policy_link)
        val spannableString = SpannableString(fullText)
        val purpleColor = ContextCompat.getColor(this, com.example.resources.R.color.app_btn_colors)
        val termsOfServiceStart = fullText.indexOf(termsOfServiceText)
        val termsOfServiceEnd = termsOfServiceStart + termsOfServiceText.length
        val termsOfServiceSpan = ForegroundColorSpan(purpleColor)
        val termsOfServiceUnderlineSpan = UnderlineSpan()
        spannableString.setSpan(termsOfServiceSpan, termsOfServiceStart, termsOfServiceEnd, 0)
        spannableString.setSpan(termsOfServiceUnderlineSpan, termsOfServiceStart, termsOfServiceEnd, 0)
        val privacyPolicyStart = fullText.indexOf(privacyPolicyText)
        val privacyPolicyEnd = privacyPolicyStart + privacyPolicyText.length
        val privacyPolicySpan = ForegroundColorSpan(purpleColor)
        val privacyPolicyUnderlineSpan = UnderlineSpan()
        spannableString.setSpan(privacyPolicySpan, privacyPolicyStart, privacyPolicyEnd, 0)
        spannableString.setSpan(privacyPolicyUnderlineSpan, privacyPolicyStart, privacyPolicyEnd, 0)
        mBinding.tvService.text = spannableString

    }




    override fun onResume() {
        super.onResume()

    }

    private fun handleUserLogin(userLoginReply: UserLoginReply) { // 公共逻辑块

        UserMKHelper.encode(UserMKHelper.SESSION, userLoginReply.session)
        UserMKHelper.encode(UserMKHelper.GUID, userLoginReply.guid)
        UserMKHelper.encode(UserMKHelper.UID, userLoginReply.user.uid)
        UserMKHelper.encode(UserMKHelper.NAME, userLoginReply.user.nickname)
        UserMKHelper.encode(UserMKHelper.HEADPIC, userLoginReply.user.headPic)
        UserMKHelper.encode(UserMKHelper.AGE, userLoginReply.user.age)
      //  UserMKHelper.encode(UserMKHelper.VIP_LEVEL, userLoginReply.user.vipLevel)
        UserMKHelper.encode(UserMKHelper.TOKEN, userLoginReply.token)
        UserMKHelper.encode(UserMKHelper.COUNTRY_CODE, userLoginReply.user.countryCode)
        UserMKHelper.encode(UserMKHelper.LANG, userLoginReply.user.lang)
        Log.e("userid", userLoginReply.user.uid.toString())
        if(!TextUtils.isEmpty(userLoginReply.user.headPic)&&TextUtils.isEmpty(UserMKHelper.decodeString(userLoginReply.user.headPic))) {
            UserMKHelper.encode(AppMkHelper.HEADPIC, userLoginReply.user.headPic)
            downloadImageAsBitmap(userLoginReply.user.headPic) { it1 ->
                if (null != it1) {
                    UserMKHelper.encode(userLoginReply.user.headPic, it1)
                }
            }
        }

        loginAgora(userLoginReply.user.uid.toString(), userLoginReply.token)
    }

    private fun loginAgora(uid: String, token: String) {
        Log.e("login", "$uid/$token")
        AgoraClient.getInstance().loginToAgora(uid, token) {
            if (it) {
                val fastLogin = LoginRequest.newBuilder().setSession(UserMKHelper.decodeString(UserMKHelper.SESSION)).build()
                viewModel.userLoginApi(fastLogin)
            } else {
                alertDialog.dismiss()
                ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        alertDialog.dismiss()

    }


    override fun getViewModelClass(): Class<LoginViewMode> = LoginViewMode::class.java


}